/**
 * Copyright(c) 2013 Jade Techonologies Co., Ltd.
 *
 * History:
 *   14-7-29 下午1:49 Created by dwzhang
 */
package com.jade.framework.base.comm.netty;

import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;

import com.jade.framework.base.comm.*;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.concurrent.DefaultEventExecutorGroup;
import io.netty.util.concurrent.EventExecutorGroup;
import org.apache.commons.lang3.StringUtils;

/**
 * 采用Netty协议实现的客户端。
 *
 * @author dwzhang
 * @version 1.0 14-7-29 下午1:49
 */
public class NettyServer
        extends AbstractServer<Channel>
{
    protected EventLoopGroup bossGroup;
    protected EventLoopGroup workerGroup;
    protected EventExecutorGroup executor;
    protected ChannelFuture bindFuture;
    protected int bossThreadCount = 0;
    protected int workerThreadCount = 0;
    protected int executorThreadCount = 0;

    public void setBossThreadCount(int bossThreadCount)
    {
        this.bossThreadCount = bossThreadCount;
    }

    public void setWorkerThreadCount(int workerThreadCount)
    {
        this.workerThreadCount = workerThreadCount;
    }

    @Override
    protected void doStart()
            throws CommException
    {
        ProtocolConfiguration configuration = protocol.getConfiguration();

        try {
            bossGroup = bossThreadCount == 0 ? new NioEventLoopGroup() : new NioEventLoopGroup(bossThreadCount);
            workerGroup = workerThreadCount == 0 ? new NioEventLoopGroup() : new NioEventLoopGroup(workerThreadCount);
            if (executorThreadCount > 0) {
                executor = new DefaultEventExecutorGroup(executorThreadCount);
            }
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(
                    new ChannelInitializer<SocketChannel>()
                    {
                        @Override
                        public void initChannel(SocketChannel ch)
                                throws Exception
                        {
                            doInitChannel(ch);
                        }
                    }).option(ChannelOption.SO_BACKLOG, configuration.getBacklog()).childOption(
                    ChannelOption.SO_KEEPALIVE,
                    true);

            // Bind and start to accept incoming connections.
            if (StringUtils.isNotBlank(configuration.getHost())) {
                bindFuture = b.bind(configuration.getHost(), configuration.getPort());
            }
            else {
                bindFuture = b.bind(configuration.getPort());
            }

            bindFuture.awaitUninterruptibly();
            if (!bindFuture.isSuccess()) {
                throw new CommException("Can't bind server!", bindFuture.cause());
            }
        }
        catch (CommException e) {
            doStop();
            throw e;
        }
        catch (Throwable t) {
            doStop();
            throw new CommException("Can't start server!", t);
        }
    }

    protected void doInitChannel(SocketChannel channel)
    {
        ChannelPipeline pipeline = channel.pipeline();
        ProtocolConfiguration configuration = protocol.getConfiguration();
        if (configuration.getPingPeriod() > 0) {
            pipeline.addLast("timeoutHandler",
                    new IdleStateHandler(0, 0, configuration.getPingPeriod(), TimeUnit.MILLISECONDS));
            pipeline.addLast("idleHandler", new NettyIdleHandler(this));
        }
        pipeline.addLast("messageDecoder", new NettyMessageDecoder(this));
        pipeline.addLast("messageEncoder", new NettyMessageEncoder(this));
        if (executor != null) {
            pipeline.addLast(executor, "serverHandler", new ServerInboundHandler(this, protocol));
        }
        else {
            pipeline.addLast("serverHandler", new ServerInboundHandler(this, protocol));
        }
    }

    public ProtocolTransport createTransport(Channel channel)
    {
        return new NettyProtocolTransport(channel, protocol);
    }

    public ProtocolSession getSession(Channel channel)
    {
        return getSession((InetSocketAddress) channel.remoteAddress());
    }

    @Override
    protected void doStop()
    {
        try {
            if (bindFuture != null) {
                bindFuture.channel().closeFuture().await(5000);
            }
        }
        catch (Throwable t) {
            protocol.getLog().warn("Can't close bind future:", t);
        }
        finally {
            if (workerGroup != null) {
                workerGroup.shutdownGracefully();
                workerGroup = null;
            }
            if (bossGroup != null) {
                bossGroup.shutdownGracefully();
                bossGroup = null;
            }

            if (executor != null) {
                executor.shutdownGracefully();
                executor = null;
            }
        }
    }
}
